package com.woniu.controller;

import com.woniu.constant.Constant;
import com.woniu.entity.Result;
import com.woniu.utils.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import com.woniu.utils.QiNiuUploadUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

    @Api(tags = "文件上传")
    @RestController
    @RequestMapping("/upload")
    public class UploadPlatformIogoController extends BaseController {

        @Autowired
        private StringRedisTemplate stringRedisTemplate;

        @ApiOperation("图片上传")
        @PostMapping("/img")
        public Result img(@RequestPart MultipartFile file) throws IOException {
            // 1. 拼接文件的名称
            String uuid = UUID.randomUUID().toString();
            String oldName = file.getOriginalFilename();
            String last = oldName.substring(oldName.lastIndexOf("."));
            String newFilename = uuid + last;
            // 2. 将用户上传的图片保存到七牛云
            QiNiuUploadUtils.uploadFile(file.getBytes(), newFilename);

            // 将图片的名称保存到Redis中
            stringRedisTemplate.opsForSet().add(Constant.REDIS_ALL_UPLOAD_IMAGE, newFilename);

            // 3. 需要将图片的名称响应给前端，做一个图片的回显
            return toDataResult(newFilename);
        }
        @ApiOperation("删除图片")
        @GetMapping("/delete")
        public Result delete(String fileName){
            QiNiuUploadUtils.deleteFile(fileName);
            return success();
        }

    }

